package butines.game.steering;

import java.util.List;

import butines.core.math2d.Vector2D;
import butines.game.steering.LocalityQueryDB.Query;

public class LocalityQueryFacility<T> implements ProximityDatabase<T> {

	private class LQTokenProximity implements Token<T>, Query {

		private LocalityQueryDB.ClientProxy bin;
		
		private LQTokenProximity(Object object) {
			bin = database.createBin(object);
		}
		
		public void notifyNewPosition(Vector2D newPosition) {
			if (bin != null) {
				database.update(bin, newPosition);
			}
		}

		public void findNeighbors(Vector2D center, float radius, List<T> results) {
			if (bin != null) {
				database.findObjects(center, radius, this, results);
			}
		}

		public void release() {
			if (bin != null) {
				database.remove(bin);
				bin = null;
			}
		}

		@SuppressWarnings("unchecked")
		public void found(Object element, float distanceSq, Object queryState) {
			((List<Object>)queryState).add(element);
		}
		
	}
	
	private LocalityQueryDB database;
	
	public LocalityQueryFacility(float originx, float originy, float sizex, float sizey, int divx, int divy) {
		database = new LocalityQueryDB(originx, originy, sizex, sizey, divx, divy);
	}

	public Token<T> allocateToken(T t) {
		return new LQTokenProximity(t);
	}

	public int count() {
		return database.count();
	}
	
}
